package com.haredot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;

@Configuration
public class RedisConfig {

    @Bean("redisTemplate")
    @Primary
    public RedisTemplate redisTemplate(@Nullable RedisConnectionFactory redisConnectionFactory) {
        Assert.notNull(redisConnectionFactory, "redisConnectionFactory 找不到");
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // GenericJackson2JsonRedisSerializer 类不能注入 ObjectMapper, 否则会导致 RedisTemplate<String, Message>
        // 类型的对象，获取 Message 对象的时候，返回的是 LinkedHashMap , 针对此代码，Message和日期相关的属性
        // 需要添加 序列化代码 和 反序列化代码 @JsonSerializer 和 @JsonDeSerializer
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer(StandardCharsets.UTF_8));
        return template;
    }

    @Bean("redisJdkTemplate")
    public RedisTemplate redisTemplateJdk(@Nullable RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) {
        Assert.notNull(redisConnectionFactory, "redisConnectionFactory 找不到");
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
